#!/bin/bash

: "${FTB_FORCE_REINSTALL:=false}"
: "${FTB_BASE_URL:=https://api.feed-the-beast.com/v1/modpacks}"
# Legacy base URL was https://api.modpacks.ch

ftbInstallMarker=".ftb-installed"

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"
isDebugging && set -x
set -e

#
#{
#  "id": 119,
#  "name": "FTB Presents Direwolf20 1.20",
#  "versionName": "1.16.0",
#  "versionId": 12252,
#  "modPackTargets": {
#    "modLoader": {
#      "name": "neoforge",
#      "version": "47.1.84"
#    },
#    "javaVersion": "17.0.7+7",
#    "mcVersion": "1.20.1"
#  },

ftbManifest=.manifest.json
function getModLoaderName() {
  jq -r ".modPackTargets.modLoader.name" ${ftbManifest}
}
function getModLoaderVersion() {
  jq -r ".modPackTargets.modLoader.version" ${ftbManifest}
}
function getMinecraftVersion() {
  jq -r ".modPackTargets.mcVersion" ${ftbManifest}
}
function getModpackName() {
  jq -r ".name" ${ftbManifest}
}
function getModpackVersion() {
  jq -r ".versionName" ${ftbManifest}
}

if [[ $(getDistro) = alpine ]]; then
  logError "The FTBA installer is not supported on Alpine. Use the java8-multiarch image tag instead."
  exit 1
fi

if ! [[ -v FTB_MODPACK_ID ]]; then
  logError "FTB_MODPACK_ID is required with TYPE=FTB"
  exit 1
fi

if ! [[ ${FTB_MODPACK_ID} =~ [0-9]+ ]]; then
  logError "FTB_MODPACK_ID needs to be numeric"
  exit 1
fi

if [[ ! $FTB_MODPACK_VERSION_ID ]]; then
  if ! FTB_MODPACK_VERSION_ID=$(curl -fsSL "${FTB_BASE_URL}/public/modpack/${FTB_MODPACK_ID}" | jq -r '.versions | sort_by(.updated)[-1].id'); then
    logError "Unable to resolve latest modpack version ID for modpack ${FTB_MODPACK_ID}"
    exit 1
  fi
elif ! [[ ${FTB_MODPACK_VERSION_ID} =~ [0-9]+ ]]; then
  logError "FTB_MODPACK_VERSION_ID needs to be numeric"
  exit 1
fi

if isTrue "$FTB_FORCE_REINSTALL" ||
  ! [ -f "${ftbManifest}" ] ||
  ! [ -f "${ftbInstallMarker}" ] ||
  [ "$(cat "${ftbInstallMarker}")" != "${FTB_MODPACK_ID}=${FTB_MODPACK_VERSION_ID}" ]; then
  ftbInstaller=/data/ftb-installer-v2
  arm=
  if ! [[ -f "${ftbInstaller}" ]]; then
    if [ "$(uname -m)" == "aarch64" ]; then
      log "Downloading FTB installer for ARM"
      arm="/arm"
    else
      log "Downloading FTB installer for x86"
    fi
    # Example: https://api.feed-the-beast.com/v1/modpacks/public/modpack/119/12252/server/linux
    #          https://api.feed-the-beast.com/v1/modpacks/public/modpack/119/12252/server/arm/linux
    # 1-1 is a placeholder modpack for just grabbing the installer
    if ! get -o "${ftbInstaller}" "${FTB_BASE_URL}/public/modpack/1/1/server${arm}/linux"; then
      logError "Failed to download FTB installer"
      exit 1
    fi
    chmod +x "${ftbInstaller}"
  fi

  log "Installing modpack ID ${FTB_MODPACK_ID}, version ID ${FTB_MODPACK_VERSION_ID}"
  log "This could take a while..."
  ${ftbInstaller} -pack "${FTB_MODPACK_ID}" -version "${FTB_MODPACK_VERSION_ID}" -auto -force | tee ftb-installer.log
  rm -f forge*installer.jar

  echo "${FTB_MODPACK_ID}=${FTB_MODPACK_VERSION_ID}" > ${ftbInstallMarker}

  writeEula

else
  log "FTB modpack ID ${FTB_MODPACK_ID}, version ID ${FTB_MODPACK_VERSION_ID} is ready to go"
fi

modLoader="$(getModLoaderName)"
modLoaderVersion="$(getModLoaderVersion)"
mcVersion=$(getMinecraftVersion)
VERSION="$mcVersion"
MODPACK_NAME=$(getModpackName)
MODPACK_VERSION=$(getModpackVersion)
export VERSION MODPACK_NAME MODPACK_VERSION

variants=(
  run.sh
  fabric-server-launch.jar
  "${modLoader}-${mcVersion}-${modLoaderVersion}-universal.jar"
  "${modLoader}-${mcVersion}-${modLoaderVersion}-${mcVersion}-universal.jar"
  "${modLoader}-${mcVersion}-${modLoaderVersion}-server-launch.jar"
  "${modLoader}-${mcVersion}-${modLoaderVersion}.jar"
)
for f in "${variants[@]}"; do
  if [ -f $f ]; then
    export SERVER=$f
    break
  fi
done
if ! [ -v SERVER ]; then
  logError "Unable to locate the installed FTB server jar"
  logError "      Tried looking for ${variants[*]}"
  exit 2
fi

# Remap the TYPE and FAMILY based on discovered server jar
if [[ $SERVER = run.sh ]]; then
  if grep -q neoforge "$SERVER"; then
    export FAMILY=FORGE
    export TYPE=NEOFORGE
  elif grep -q forge "$SERVER"; then
    export FAMILY=FORGE
    export TYPE=FORGE
  elif grep -q fabric run.s; then
      export FAMILY=FABRIC
      export TYPE=FABRIC
  else
    logError "Unrecognized loader type in $SERVER"
    cat "$SERVER"
    exit 1
  fi

elif [[ $SERVER = forge* ]]; then
  export FAMILY=FORGE
  export TYPE=FORGE
elif [[ $SERVER = fabric* ]]; then
  export FAMILY=FABRIC
  export TYPE=FABRIC
else
  logError "Unrecognized loader type from $SERVER"
  exit 1
fi

exec "$(dirname "$0")/start-setupWorld" "$@"
